const Users = require('../../models/users')
const jwt = require('jsonwebtoken')
const {v4: uuidv4} = require('uuid')
const Token = require('../../models/token')
const process = require('node:process')
const postLogin = async (req, res) => {
  try {
    const user = await Users.findOne({email: req.body.email})

    if (!user) {
      return res.status(403).json({success: false, msg: 'User not found'})
    }
    const validate = await user.isValidPassword(req.body.password)

    if (!validate) {
      return res.status(403).json({success: false, msg: 'Wrong Password or email'})
    }

    const deviceId = uuidv4()
    const accessToken = jwt.sign({user: user}, process.env.SECRET_KEY, {expiresIn: '1d'})
    const refreshToken = jwt.sign({user: user, deviceId}, process.env.SECRET_KEY, {
      expiresIn: '30d',
    })

    await Token.create({
      id: uuidv4(),
      userId: user._id,
      token: refreshToken,
      device: deviceId,
      date: new Date(),
    })

    return res.status(200).json({
      success: true,
      user: user,
      accessToken,
      refreshToken,
      expireToken: new Date().getTime() + 24 * 3600 * 1000,
    })
  } catch (err) {
    return res.status(500).json({success: false, msg: err.message})
  }
}

module.exports = {
  postLogin,
}
